package com.sky.aspect;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.time.LocalDateTime;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import com.sky.annotation.AutoFill;
import com.sky.constant.AutoFillConstant;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;


import lombok.extern.slf4j.Slf4j;

@Component
@Aspect
@Slf4j
public class AutoFillAspect {
  /* 
   * 切面类，用于在方法执行前后自动填充数据
   */

  @Pointcut("execution(* com.sky.mapper.*.*(..))&&@annotation(com.sky.annotation.AutoFill)")
  public void autoFillPointCut(){}  

/* 
 * 前置通知,为公共字段赋值
 */
  @Before("autoFillPointCut()")
  public void autoFill(JoinPoint joinPoint) throws NoSuchMethodException, SecurityException, Exception, Exception, Exception{
    log.info("开始执行自动填充");

    MethodSignature signature =  (MethodSignature) joinPoint.getSignature();
    AutoFill autoFill = signature.getMethod().getAnnotation(AutoFill.class);
    OperationType operationType = autoFill.value();

    Object[] args = joinPoint.getArgs();
    if(args.length == 0){
      log.info("没有参数");
      return;
    }
    Object obj = args[0];
    LocalDateTime now = LocalDateTime.now();
    Long userId = BaseContext.getCurrentId();

    if(operationType == OperationType.INSERT){
      Method setCreateTime = obj.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
     
      Method setUpdateTime = obj.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
     
      Method setCreateUser = obj.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_USER, Long.class);
      Method setUpdateUser = obj.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
      setCreateTime.invoke(obj, now);
      setUpdateTime.invoke(obj, now);
      setCreateUser.invoke(obj, userId);
      setUpdateUser.invoke(obj, userId);
    }
    else if(operationType == OperationType.UPDATE){
  
      Method setUpdateTime = obj.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
     
    
      Method setUpdateUser = obj.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
      
      setUpdateTime.invoke(obj, now);
      
      setUpdateUser.invoke(obj, userId);
    }

  
  }
}
